/*
 * Copyright (C) 2013 TinhVan Outsourcing.
 */
package com.ascendere9.ff.pof.util;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class LocationTracking implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {

	private static final String LOG_TAG = "LocationTracking";
	private static final int LOCATION_UPDATE_TIME = 30000;
	private static final LocationRequest REQUEST = LocationRequest.create().setInterval(LOCATION_UPDATE_TIME)
			.setFastestInterval(16).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

	private static LocationTracking mInstance;
	private Context context;
	private Location mCurrentLocation;
	private LocationClient mLocationClient;

	private LocationTracking() {
	}

	public static LocationTracking getInstance() {
		if (mInstance == null) {
			mInstance = new LocationTracking();
		}
		return mInstance;
	}

	public void connect(Context context) {
		this.context = context;
		if (mLocationClient != null && mLocationClient.isConnected()) {
			mLocationClient.disconnect();
		}
		this.setUpLocationClientIfNeeded();
	}

	public Location getCurrentLocation() {
		return mCurrentLocation;
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(this.context, this, this);
		}
		mLocationClient.connect();
	}

	@Override
	public void onLocationChanged(Location location) {
		mCurrentLocation = location;
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
	}

	@Override
	public void onConnected(Bundle arg0) {
		mLocationClient.requestLocationUpdates(REQUEST, this);
	}

	@Override
	public void onDisconnected() {
	}

	public void destroy() {
		if (mLocationClient != null && mLocationClient.isConnected()) {
			mLocationClient.removeLocationUpdates(LocationTracking.this);
			mLocationClient.disconnect();
		}
		context = null;
		mCurrentLocation = null;
		mInstance = null;
	}
}
